package org.dromara.signIn.controller;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.List;

import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.signIn.domain.vo.SignInTaskVo;
import org.dromara.signIn.service.ISignInTaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.signIn.domain.vo.SignInRecordVo;
import org.dromara.signIn.domain.bo.SignInRecordBo;
import org.dromara.signIn.service.ISignInRecordService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 签到记录
 *
 * @author Lion Li
 * @date 2025-09-25
 */
@Validated
@RestController
@RequestMapping("/signIn/record")
public class SignInRecordController extends BaseController {

    private final ISignInRecordService signInRecordService;
    private final ISignInTaskService signInTaskService;

    private final ZoneId systemDefault;

    @Value("${sign-in.available-ip-address}")
    String availableIpAddress;

    public SignInRecordController(ISignInTaskService signInTaskService, ISignInRecordService signInRecordService) {
        this.signInTaskService = signInTaskService;
        this.signInRecordService = signInRecordService;
        this.systemDefault = ZoneId.systemDefault();
    }

    /**
     * 查询签到记录列表
     */
//    @SaCheckPermission("signIn:record:list")
    @GetMapping("/list")
    public TableDataInfo<SignInRecordVo> list(SignInRecordBo bo, PageQuery pageQuery) {
        return signInRecordService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询用户签到情况
     * @param userId 用户id
     * @return 用户今日签到情况(0 没签到,1 已签到,2 已签退)
     */
//    @SaCheckPermission("signIn:record:list")
    @GetMapping("/getUserTaskSignInRecord")
    public TableDataInfo<SignInRecordVo> getUserTaskSignInRecord(Long userId, Long taskId) {
        List<SignInRecordVo> result = signInRecordService.counterToday(userId, taskId);
        return TableDataInfo.build(result);
    }

    /**
     * 导出签到记录列表
     */
    @SaCheckPermission("signIn:record:export")
    @Log(title = "签到记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SignInRecordBo bo, HttpServletResponse response) {
        List<SignInRecordVo> list = signInRecordService.queryList(bo);
        ExcelUtil.exportExcel(list, "签到记录", SignInRecordVo.class, response);
    }

    /**
     * 获取签到记录详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("signIn:record:query")
    @GetMapping("/{id}")
    public R<SignInRecordVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(signInRecordService.queryById(id));
    }

    /**
     * 新增签到记录
     */
//    @SaCheckPermission("signIn:record:add")
    @Log(title = "签到记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SignInRecordBo bo) {
        int counter = signInRecordService.counterToday(bo.getUserId(), bo.getTaskId()).size();

        SignInTaskVo signInTaskVo = signInTaskService.queryById(bo.getTaskId());
        if (signInTaskVo != null) {
            LocalTime startTime = signInTaskVo.getStartTime().toInstant().atZone(systemDefault).toLocalTime();
            LocalTime endTime = signInTaskVo.getEndTime().toInstant().atZone(systemDefault).toLocalTime();
            LocalTime now = LocalTime.now(systemDefault);
            if (now.isBefore(startTime) || now.isAfter(endTime)) {
                throw new RuntimeException("当前不在签到（签退）时间范围内");
            }
        }

        //签到
        if (counter == 0) {
            return toAjax(signInRecordService.insertByBo(bo));
        }
        //签退
        if (counter == 1) {
            SignInRecordVo lastSignInRecord = signInRecordService.findLastSignInRecord(bo);
            bo.setRelatedSignId(lastSignInRecord.getId());
            return toAjax(signInRecordService.insertByBo(bo));
        }
        if (counter >= 2) {
            throw new RuntimeException("签到次数为:"+counter);
        }
        //异常
        throw new RuntimeException("签到情况异常,请刷新页面");
    }

    /**
     * 修改签到记录
     */
//    @SaCheckPermission("signIn:record:edit")
    @Log(title = "签到记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SignInRecordBo bo) {
        return toAjax(signInRecordService.updateByBo(bo));
    }

    /**
     * 删除签到记录
     *
     * @param ids 主键串
     */
    @SaCheckPermission("signIn:record:remove")
    @Log(title = "签到记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(signInRecordService.deleteWithValidByIds(List.of(ids), true));
    }
}
